package handler

import (
	"ginadmin/models"
	ctx "ginadmin/routes/context"
	"ginadmin/utils"
	"github.com/gin-gonic/gin"
)

type UserHandler struct {
}

func (user *UserHandler) Router(group *gin.RouterGroup) {
	group.GET("/user/list", user.List)
	group.POST("/user/add", user.Add)
	group.POST("/user/dels", user.Dels)
	group.POST("/user/changepwd", user.ChangePwd)
}

func (role *UserHandler) ChangePwd(c *gin.Context) {
	newpwd := c.PostForm("pwdkey")
	userid := c.PostForm("userid")
	if newpwd == "" {
		ctx.Err(c, 400, "密码不能为空")
		return
	}

	if userid == "" {
		ctx.Err(c, 400, "用户id不能为空")
		return
	}
	r := &models.User{}
	err := r.UpdatePwd(utils.StrToUInt(userid), utils.HashAndSalt([]byte(newpwd)))
	if err != nil {
		ctx.Err(c, 400, err.Error())
		return
	}
	ctx.OK(c)
}

func (role *UserHandler) Dels(c *gin.Context) {
	req := c.Request
	users := req.FormValue("users")
	if users == "" {
		ctx.Err(c, 400, "删除用户不能为空")
		return
	}
	r := &models.User{}
	err := r.Dels(users)
	if err != nil {
		ctx.Err(c, 400, err.Error())
		return
	}
	ctx.OK(c)
}

func (user *UserHandler) Add(c *gin.Context) {
	req := c.Request
	name := req.FormValue("name")
	userName := req.FormValue("userName")
	pwdkey := req.FormValue("pwdkey")
	roleId := req.FormValue("roleselect")
	orgId := req.FormValue("parentId")

	if roleId == "" {
		ctx.Err(c, 400, "角色ID不能为空")
		return
	}

	r := &models.Role{}
	err := r.FindById(utils.StrToUInt(roleId))
	if err != nil {
		ctx.Err(c, 400, err.Error())
		return
	}

	if orgId == "" {
		ctx.Err(c, 400, "所属机构不能为空")
		return
	}

	if pwdkey == "" {
		ctx.Err(c, 400, "密码不能为空")
		return
	}

	if name == "" {
		ctx.Err(c, 400, "用户名称不能为空")
		return
	}

	if userName == "" {
		ctx.Err(c, 400, "登录名不能为空")
		return
	}

	//查询username是否已存在，如果存在报错
	u := &models.User{}
	err = u.FindByUsername(userName)

	if err == nil {
		ctx.Err(c, 400, "登录名已存在")
		return
	}

	password := utils.HashAndSalt([]byte(pwdkey))
	u = &models.User{Name: name, UserName: userName, Password: password,
		Role: r.Name, Roleid: utils.StrToUInt(roleId), OrgId: utils.StrToUInt(orgId)}
	u.Add()
	ctx.OK(c)
}

func (user *UserHandler) List(c *gin.Context) {
	orgList, err := models.UserList()
	if err != nil {
		ctx.Map(c, ctx.M{"code": 401, "msg": err.Error(), "data": nil})
		return
	}
	ctx.Map(c, ctx.M{"code": 200, "msg": "OK", "data": orgList})
}
